package ru.stepanovdn.trading.server.service.tinkoff

import org.springframework.beans.factory.annotation.Value
import ru.tinkoff.piapi.contract.v1.Account
import ru.tinkoff.piapi.contract.v1.AccountType
import java.util.function.Consumer

import ru.tinkoff.piapi.core.InvestApi
import jakarta.annotation.PostConstruct
import org.slf4j.LoggerFactory

abstract class ATinkoffAPI : ITinkoffCommonAPI, ITinkoffOrderAPI {

    val log = LoggerFactory.getLogger(javaClass)

    @Value("\${tinkoff.token}")
    private val token: String? = null

    @Value("\${tinkoff.account-id}")
    override var accountId: String? = null

    @Value("\${tinkoff.is-token-sandbox:false}")
    override val isSandboxMode: Boolean = false

    override var api: InvestApi? = null

    @PostConstruct
    private fun init() {
        api = if (isSandboxMode) InvestApi.createSandbox(token!!, "stepanovdn") else InvestApi.create(
            token!!,"stepanovdn"
        )

        // Проверяем, что аккаунт существует (если задан в конфигах) или выбираем первый
        val accounts: List<Account> = if (isSandboxMode) api!!.sandboxService.accountsSync else api!!.userService.accountsSync
        log.info("Available accounts: {}", accounts.size)
        accounts.forEach(Consumer { a: Account -> log.info("Account id {}, name {}", a.id, a.name) })
        val account = accounts.stream()
            .filter { a: Account -> a.type == AccountType.ACCOUNT_TYPE_TINKOFF }
            .filter { a: Account -> accountId == null || accountId!!.isEmpty() || accountId == a.id }
            .findFirst().orElseThrow { RuntimeException("Account was not found for token $token") }
        log.info("Will use Account id {}, name {}", account.id, account.name)
        accountId = account.id
    }
}
